import { CanActivate, ExecutionContext, HttpException, HttpStatus, Inject, Injectable } from '@nestjs/common';
import { Request } from 'express';
import { UserService } from './user/user.service';
import { Permission } from './user/entities/permission.entity';
import { Reflector } from '@nestjs/core';

@Injectable()
export class PermissionGuard implements CanActivate {

  @Inject(UserService) 
  private userService: UserService;

  @Inject(Reflector)
  private reflector: Reflector;

  async canActivate(
    context: ExecutionContext,
  ): Promise<boolean> {
    const request: Request = context.switchToHttp().getRequest();

    if(!request.user) {
      return true;
    }
    const roles = await this.userService.findRolesByIds(request.user.roles.map((item:any) => item.id))

    const permissions: Permission[]  = roles.reduce((total:any, current:any) => {
      return [...total, ...current.permission];
    }, []);

    const requiredPermissions = this.reflector.getAllAndOverride<string>('require-permission', [context.getHandler(), context.getClass()]);

    console.log(requiredPermissions,11)
    if(requiredPermissions && !permissions.some((item:Permission) => item.name === requiredPermissions)){
      throw new HttpException('权限不足',HttpStatus.FORBIDDEN);
    }

    return true;
  }
}